const router = require('koa-router')()
const { pool } = require('../config/database')
const { authMiddleware } = require('../middleware/auth')

router.prefix('/api/favorite')

// 获取收藏列表
router.get('/', authMiddleware, async (ctx) => {
  try {
    const [favorites] = await pool.execute(
      'SELECT * FROM user_favorites WHERE user_id = ?',
      [ctx.user.userId]
    )
    
    ctx.body = {
      code: 200,
      message: '获取收藏列表成功',
      data: favorites
    }
  } catch (error) {
    console.error('获取收藏列表错误:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '获取收藏列表失败',
      error: error.message
    }
  }
})

// 添加/移除收藏
router.post('/', authMiddleware, async (ctx) => {
  const { songId, action } = ctx.request.body
  
  try {
    if (action === 'add') {
      // 检查是否已收藏
      const [existing] = await pool.execute(
        'SELECT id FROM user_favorites WHERE user_id = ? AND song_id = ?',
        [ctx.user.userId, songId]
      )
      
      if (existing.length > 0) {
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: '歌曲已在收藏列表中'
        }
        return
      }
      
      await pool.execute(
        'INSERT INTO user_favorites (user_id, song_id) VALUES (?, ?)',
        [ctx.user.userId, songId]
      )
      
      ctx.body = {
        code: 200,
        message: '收藏成功'
      }
    } else if (action === 'remove') {
      await pool.execute(
        'DELETE FROM user_favorites WHERE user_id = ? AND song_id = ?',
        [ctx.user.userId, songId]
      )
      
      ctx.body = {
        code: 200,
        message: '取消收藏成功'
      }
    } else {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '无效的操作类型'
      }
    }
  } catch (error) {
    console.error('收藏操作错误:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '收藏操作失败',
      error: error.message
    }
  }
})

module.exports = router